package com.huluobo.a2201mvvm_imdemo.chat;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.huluobo.a2201mvvm_imdemo.R;
import com.huluobo.a2201mvvm_imdemo.adapter.MessageAdapter;
import com.huluobo.a2201mvvm_imdemo.databinding.ActivityMyChatBinding;
import com.huluobo.a2201mvvm_imdemo.mvvm.BaseMVVMActivity;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;

import java.util.ArrayList;
import java.util.List;

public class MyChatActivity extends BaseMVVMActivity<ActivityMyChatBinding, ChatViewModel> {
    private String conversationId;
    private int chatType;

    private MessageAdapter messageAdapter;

    private List<EMMessage> messageList = new ArrayList<>();

    private EMMessageListener messageListener = messages -> {
        runOnUiThread(() -> {
            messageList.addAll(messages);
            messageAdapter.notifyDataSetChanged();
            scrollToBottom();
            EMConversation conversation = EMClient.getInstance().chatManager().getConversation(conversationId);
            conversation.markAllMessagesAsRead();
        });

    };

    @Override
    protected void initData() {
        viewModel.sendSuccess.observe(this, emMessage -> {
            messageList.add(emMessage);
            messageAdapter.notifyDataSetChanged();
            dataBinding.myChatInputEt.setText("");
            scrollToBottom();
        });

        viewModel.sendFailed.observe(this, s -> {
            Log.i("TagA", "发送消息失败:" + s);
        });
    }

    private void scrollToBottom() {
//        dataBinding.myChatRv.scrollToPosition(messageList.size()-1);
        //平滑移动到对应的位置
        dataBinding.myChatRv.smoothScrollToPosition(messageList.size() - 1);
    }

    @Override
    protected void initView() {
        conversationId = getIntent().getStringExtra("conversationId");
        chatType = getIntent().getIntExtra("chatType", 0);

        dataBinding.myChatSendIv.setOnClickListener(v -> {
            viewModel.sendMessage(
                    dataBinding.myChatInputEt.getText().toString(),
                    conversationId,
                    chatType
            );
        });

        dataBinding.myChatHeader.headerTitle.setText("正在与" + conversationId + "聊天");
        dataBinding.myChatHeader.headerBack.setVisibility(View.VISIBLE);
        dataBinding.myChatHeader.headerBack.setOnClickListener(v -> {
            finish();
        });

        dataBinding.myChatRv.setLayoutManager(new LinearLayoutManager(this));
        messageAdapter = new MessageAdapter(messageList);
        dataBinding.myChatRv.setAdapter(messageAdapter);

        //添加消息监听器
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(conversationId);
        conversation.markAllMessagesAsRead();

        if (conversation.getAllMessages().size() != 0) {
            messageList.addAll(conversation.getAllMessages());//在数据源中加入所有历史消息
            messageAdapter.notifyDataSetChanged();
        }

        dataBinding.myChatSrl.setOnRefreshListener(() -> {
            String startId = messageList.get(0).getMsgId();//查询历史消息记录的起始位置,也就是当前聊天数据源的第0位
            List<EMMessage> emMessages = conversation.loadMoreMsgFromDB(startId, 10);
            messageList.addAll(0, emMessages);//加载历史聊天记录时,不能从list的末尾添加,也就是不能直接addAll,从第0位开始添加
            messageAdapter.notifyDataSetChanged();
            dataBinding.myChatSrl.setRefreshing(false);
            dataBinding.myChatRv.scrollToPosition(emMessages.size()+1);
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
    }

    @Override
    protected Class<ChatViewModel> getViewModel() {
        return ChatViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_chat;
    }
}